package com.core.family.admin.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.core.family.admin.domain.FileLogic;
import com.core.family.admin.domain.FileStorage;
import com.core.family.admin.mapper.FileLogicMapper;
import com.core.family.admin.service.FileStorageService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.core.family.admin.mapper.FileLogicMapper;
import com.core.family.admin.service.FileLogicService;
import com.core.common.gen.BaseServiceImpl;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.Serializable;
import java.util.Objects;


/**
 * @author honglei
 * @version 1.0
 * @time: 2023-6-14 17:05:08
 * @Description 服务实现层 文件逻辑存储
 */
@Slf4j
@Service
public class FileLogicServiceImpl extends BaseServiceImpl<FileLogicMapper, FileLogic> implements FileLogicService {

    @Autowired
    FileStorageService fileStorage;


    @Override
    public FileLogic saveFile(MultipartFile file, String id) throws IOException {

        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf(".")); //获取文件后缀
        String contentType = file.getContentType();


        FileStorage storage = fileStorage.createWithcheck(file.getInputStream(), suffixName);

        FileLogic storageLogic = new FileLogic()
                .setId(id)
                .setFileName(fileName)
                .setStorageId(storage.getId())
                .setFileUrl(storage.getFileUrl())
                .setFileKey(storage.getFileKey());

        this.saveOrUpdate(storageLogic);

        return storageLogic;
    }

    @Override
    public FileLogic getByIdOrkeyName(String keyName, String id) {
        LambdaQueryWrapper<FileLogic> wrapper = new LambdaQueryWrapper();
        wrapper.eq(Objects.nonNull(keyName), FileLogic::getFileKey, keyName)
                .eq(Objects.nonNull(id), FileLogic::getId, id);

        return getOne(wrapper);

    }
}

